package com.bh.order.service.impl;

import com.bh.common.constant.Entity;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.MapUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.bean.BeanUtils;
import com.bh.extend.domain.JcCustomerPrice;
import com.bh.extend.domain.JcCustomerVolumePrice;
import com.bh.extend.domain.JcOrderBarcode;
import com.bh.extend.domain.JcReceivingParty;
import com.bh.extend.mapper.JcOrderBarcodeMapper;
import com.bh.extend.service.IJcCustomerPriceService;
import com.bh.extend.service.IJcOrderBarcodeService;
import com.bh.extend.service.IJcReceivingPartyService;
import com.bh.extend.vo.JcCustomerPriceQueryVo;
import com.bh.fee.domain.JcFeeType;
import com.bh.fee.service.IJcFeeTypeService;
import com.bh.kysys.domain.JcSysOrganization;
import com.bh.kysys.service.IJcZoneService;
import com.bh.ledger.domain.JcLedgerDetail;
import com.bh.ledger.mapper.JcLedgerDetailMapper;
import com.bh.ledger.service.IJcLedgerDetailService;
import com.bh.order.domain.JcOrder;
import com.bh.order.domain.JcOrderProduct;
import com.bh.order.domain.JcOrderReceivingParty;
import com.bh.order.mapper.JcOrderMapper;
import com.bh.order.service.IJcOrderHandleService;
import com.bh.order.service.IJcOrderReceivingPartyService;
import com.bh.order.vo.JcOrderImportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 專門处理异步功能
 * @author Administrator
 * @date 2023/09/04
 */

@Service
public class JcOrderHandleServiceImpl implements IJcOrderHandleService {

    @Autowired
    private IJcReceivingPartyService jcReceivingPartyService;
    @Autowired
    private IJcOrderBarcodeService jcOrderBarcodeService;
    @Autowired
    private JcOrderBarcodeMapper jcOrderBarcodeMapper;
    @Autowired
    private IJcZoneService jcZoneService;
    @Autowired
    private IJcOrderReceivingPartyService jcOrderReceivingPartyService;
    @Autowired
    private IJcFeeTypeService feeTypeService;
    @Autowired
    private IJcLedgerDetailService jcLedgerDetailService;
    @Autowired
    private JcLedgerDetailMapper jcLedgerDetailMapper;
    @Autowired
    private JcOrderMapper jcOrderMapper;
    @Autowired
    private IJcCustomerPriceService jcCustomerPriceService;
    /**
     * 处理收发货方存储(客户的地址，不关联)
     *
     * @param orderReceivingParty
     */
    @Override
    public void handyRp(JcOrderReceivingParty orderReceivingParty, Long jcFromOrToOrganizationId, Long customerId, Long serverZoneId) {
        // 需要进行全匹配
        if (StringUtils.isNotEmpty(orderReceivingParty.getAddress())
                && StringUtils.isNotEmpty(orderReceivingParty.getContactperson())
                && StringUtils.isNotEmpty(orderReceivingParty.getLtl())
                && StringUtils.isNotEmpty(orderReceivingParty.getName())
                && StringUtils.isNotEmpty(orderReceivingParty.getIphone())) {
            JcReceivingParty query = new JcReceivingParty();
            BeanUtils.copyProperties(orderReceivingParty, query);
            query.setJcServerZoneId(serverZoneId);
            query.setJcOrganizationId(jcFromOrToOrganizationId);

            List<JcReceivingParty> receivingParties = jcReceivingPartyService.selectJcReceivingpartyList(query);
            //如果没有
            if (receivingParties.size() == 0 && StringUtils.isNotBlank(customerId) && StringUtils.isNotBlank(orderReceivingParty.getLtl())) {
                JcReceivingParty receivingParty = new JcReceivingParty();
                receivingParty.setJcOrganizationId(jcFromOrToOrganizationId);
                receivingParty.setStatus(Entity.ACTIVE);
                receivingParty.setContactperson(orderReceivingParty.getContactperson());
                receivingParty.setAddress(orderReceivingParty.getAddress());
                receivingParty.setAddressType(orderReceivingParty.getAddressType());
                receivingParty.setLtl(orderReceivingParty.getLtl());
                if (orderReceivingParty.getJcZoneId() == null) {
                    orderReceivingParty.setJcZoneId(MapUtils.getAdcode(orderReceivingParty.getLtl()));
                }
                receivingParty.setCustomerId(customerId);
                receivingParty.setName(orderReceivingParty.getName());
                receivingParty.setIphone(orderReceivingParty.getIphone());
                receivingParty.setDescription(orderReceivingParty.getDetaileAddress());
                receivingParty.setDetaileAddress(orderReceivingParty.getDetaileAddress());
                receivingParty.setJcZoneId(MapUtils.getAdcode(orderReceivingParty.getLtl()));
                receivingParty.setJcServerZoneId(serverZoneId);
                jcReceivingPartyService.insertJcReceivingparty(receivingParty);
            }
        }
    }


    @Override
    public void handleOrderBarcode(JcOrder jcOrder, List<JcOrderProduct> orderProducts) {
        //新增
        List<JcOrderBarcode> codes = new ArrayList<>();
        // 此处采用更新
        for (JcOrderProduct orderProduct : orderProducts) {
            // 保存二维码
            if (orderProduct.getNumber() > 0) {
                for (int i = 0; i < orderProduct.getNumber(); i++) {
                    JcOrderBarcode orderBarcode = new JcOrderBarcode();
                    orderBarcode.setOrderId(jcOrder.getId());
                    orderBarcode.setProductId(orderProduct.getId());
                    orderBarcode.setPackStatus("N");
                    codes.add(orderBarcode);
                }
            }
        }
        // 先删除
        jcOrderBarcodeMapper.deleteByOrderIds(List.of(jcOrder.getId()));
        int coedSize = codes.size();
        if (coedSize > 0) {
            for (int i = 0; i < coedSize; i++) {
                JcOrderBarcode code = codes.get(i);
                code.setProductCode(jcOrder.getCode() + "N" + (i + 1));
                code.setOrderBy(String.format("%04d", i + 1));
                jcOrderBarcodeService.insertJcOrderBarcode(code);
            }
        }
    }

    /**
     *
     * @param importVo  导入数据
     * @param organization 出发网点
     */
    @Override
    public void handleFromAndToAddress(JcOrderImportVo importVo, JcSysOrganization organization, JcOrder order) {
        List<JcOrderReceivingParty> orderReceivingParties = new ArrayList<>();
        JcOrderReceivingParty from = new JcOrderReceivingParty();
        if (StringUtils.isBlank(organization.getAddress())) {
            // 手动添加数据
            String message = "没有查找到该目的运点，请添加目的运点! ";
            throw new ServiceException(message);
        }
        from.setJcOrderId(order.getId());
        from.setAddressType(importVo.getFromAddressType());
        from.setContactperson(importVo.getFromContactperson());
        from.setIphone(importVo.getFromIphone());
        from.setName(importVo.getCustomerName());

        from.setAddress(organization.getAddress());
        from.setDetaileAddress(organization.getAddress());
        from.setLtl(organization.getLatitude());

        from.setStatus(Entity.ACTIVE);
        Map<String, String> fromMap = jcZoneService.selectJcZoneByZoneNames(importVo.getJcStartZoneIdName());
        if (StringUtils.isNotBlank(fromMap.get("lastZoneId"))) {
            from.setJcZoneId(Long.valueOf(fromMap.get("lastZoneId")));
        }
        from.setType(0);
        from.setCreateName(order.getCreateName());
        from.setCreateTime(order.getCreateTime());
        orderReceivingParties.add(from);

        // 收货方
        JcOrderReceivingParty to = new JcOrderReceivingParty();
        to.setJcOrderId(order.getId());
        to.setAddress(importVo.getToAddress());
        to.setDetaileAddress(importVo.getToAddress());
        to.setAddressType(importVo.getToAddressType());
        to.setName(importVo.getToCustomerName());
        to.setContactperson(importVo.getToCustomerName());
        to.setIphone(importVo.getToIphone());
        to.setStatus(Entity.ACTIVE);
        if (StringUtils.isNotBlank(importVo.getToStreetCode())) {
            to.setJcZoneId(Long.valueOf(importVo.getToStreetCode()));
        } else if (StringUtils.isNotBlank(importVo.getJcEndZoneIdName())) {
            Map<String, String> toMap = jcZoneService.selectJcZoneByZoneNames(importVo.getJcEndZoneIdName());
            if (StringUtils.isNotBlank(toMap.get("lastZoneId"))) {
                to.setJcZoneId(Long.valueOf(toMap.get("lastZoneId")));
            }
        }
        JcReceivingParty toReceivingParty = jcReceivingPartyService.selectJcReceivingpartyListByName(importVo.getToAddress());
        if (toReceivingParty != null && StringUtils.isNotBlank(toReceivingParty.getLtl())) {
            to.setLtl(toReceivingParty.getLtl());
        } else {
            to.setLtl(MapUtils.getLonAndLatString(importVo.getToAddress()));
        }
        to.setType(1);
        to.setCreateName(order.getCreateName());
        to.setCreateTime(DateUtils.getNowDate());
        orderReceivingParties.add(to);
        jcOrderReceivingPartyService.saveBatch(orderReceivingParties);
    }


    /**
     * 从页面手动添加的台账
     * @param jcOrder
     * @param addressType
     * @return
     */
    @Override
    public void handleAddLedgerDetail(JcOrder jcOrder, String addressType) {
        // 费用， 获取台账信息
        BigDecimal incomePrice = BigDecimal.ZERO;
        List<JcLedgerDetail> ledgerDetails = jcOrder.getLedgerDetails();
        // 处理并保存数据
        if (ledgerDetails != null && !ledgerDetails.isEmpty()) {
            BigDecimal whxje = BigDecimal.ZERO; //未核销金额
            BigDecimal agent = BigDecimal.ZERO; //代收货款
            // 先删除
            jcLedgerDetailMapper.deleteByOrderIds(List.of(jcOrder.getId()));
            List<JcLedgerDetail> newLedgerDetails = new ArrayList<>();
            for (JcLedgerDetail ledgerDetail : ledgerDetails) {
                BigDecimal amount = ledgerDetail.getAmount();
                whxje = whxje.add(ledgerDetail.getAmount());
                if (amount.compareTo(BigDecimal.ZERO) > 0) {
                    //处理代收货款
                    JcFeeType feeType = feeTypeService.selectJcFeeTypeById(ledgerDetail.getJcFeeTypeId());
                    if (feeType.getIsCount() != null && ledgerDetail.getIncome().compareTo(BigDecimal.ZERO) > 0) {
                        int isCount = feeType.getIsCount();
                        if (isCount == 1) {
                            //如果是代收代付类的
                            agent = agent.add(amount);
                        }
                    }
                    ledgerDetail.setJcOrderId(jcOrder.getId());
                    ledgerDetail.setCategory(1);
                    ledgerDetail.setType(0);
                    ledgerDetail.setStatus(Entity.ACTIVE);
                    ledgerDetail.setIsConfirm(0);
                    ledgerDetail.setCreateName(jcOrder.getCreateName());
                    ledgerDetail.setCreateTime(DateUtils.getNowDate());
                    newLedgerDetails.add(ledgerDetail);
                }
            }
            if (!newLedgerDetails.isEmpty()) {
                jcLedgerDetailService.saveBatch(newLedgerDetails);
            }
            jcOrder.setWhxMoney(whxje);
            jcOrder.setAgent(agent);
            jcOrder.setPrice(incomePrice);
            jcOrderMapper.updateById(jcOrder);
        }
    }
}
